package test.demos.ireport.utils;

import java.math.BigDecimal;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRField;

public class CustomDataSource implements JRDataSource {

	protected List<Object> dataList;

	protected int index = -1;

	private static final Logger log = LoggerFactory.getLogger(CustomDataSource.class);

	public CustomDataSource(List<Object> dataList) {
		super();
		this.dataList = dataList;
	}

	@Override
	public boolean next() throws JRException {
		index++;
		return (index < dataList.size());
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Object getFieldValue(JRField field) throws JRException {
		try {
			String fieldName = field.getName();
			String firstCharater = fieldName.substring(0, 1);
			String firstCharaterToUpper = firstCharater.toUpperCase();
			fieldName = fieldName.replaceFirst(firstCharater, firstCharaterToUpper);
			Object object = (Object) dataList.get(index);
			Object addResult = null;
//			if (object instanceof MaterialMaster) {
//				MaterialMaster to = (MaterialMaster) object;
//				Class classType = to.getClass();
//				// log.info("[getFieldValue] fieldName = " + fieldName);
//				Method getMethod = classType.getMethod("get" + fieldName);
//				addResult = getMethod.invoke(to);
//			}
			if (addResult != null) {
				if (addResult instanceof Integer) {
					return ((Integer) addResult).toString();
				}
				if (addResult instanceof Long) {
					return ((Long) addResult).toString();
				}
				if (addResult instanceof BigDecimal) {
					return String.valueOf((BigDecimal) addResult);
				}
				// if (addResult instanceof Boolean) {
				// return BooleanUtil.convertToDBBooleanString((Boolean)
				// addResult);
				// }
				// if (addResult instanceof Date) {
				// return String.valueOf(DateUtil.formatDate((Date) addResult));
				// }
			}
			return addResult;
		} catch (Exception e) {
			log.error("" + e.getMessage());
			return null;
		}
	}
}
